package com.yfqy.app.modules.wechat.controller;


import com.yfqy.app.modules.wechat.model.WechatPayOrderRequest;
import com.yfqy.app.modules.wechat.model.WechatPayOrderResponse;
import com.yfqy.app.modules.wechat.model.WechatRefundRequest;
import com.yfqy.app.modules.wechat.model.WechatRefundResponse;
import com.yfqy.app.modules.wechat.service.WechatPayService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/client/wechat/pay")
@Slf4j
public class WechatPayController {

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createOrder(@Valid @RequestBody WechatPayOrderRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            WechatPayOrderResponse response = wechatPayService.createOrder(request);
            if (response != null && "SUCCESS".equals(response.getReturnCode()) &&
                    "SUCCESS".equals(response.getResultCode())) {
                result.put("success", true);
                result.put("data", response);
                result.put("message", "创建订单成功");
            } else {
                result.put("success", false);
                result.put("data", response);
                result.put("message", response != null ? response.getReturnMsg() : "创建订单失败");
            }
        } catch (Exception e) {
            log.error("创建订单异常", e);
            result.put("success", false);
            result.put("message", "创建订单异常: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 生成小程序支付参数
     */
    @PostMapping("/jsapi")
    public ResponseEntity<Map<String, Object>> generateJsApiParams(@Valid @RequestBody WechatPayOrderRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 先创建订单
            WechatPayOrderResponse orderResponse = wechatPayService.createOrder(request);
            if (orderResponse != null && "SUCCESS".equals(orderResponse.getReturnCode()) &&
                    "SUCCESS".equals(orderResponse.getResultCode())) {

                // 2. 生成小程序支付参数
                Map<String, String> jsApiParams = wechatPayService.generateJsApiParams(orderResponse.getPrepayId());

                result.put("success", true);
                result.put("data", jsApiParams);
                result.put("message", "生成支付参数成功");
            } else {
                result.put("success", false);
                result.put("data", orderResponse);
                result.put("message", orderResponse != null ? orderResponse.getReturnMsg() : "创建订单失败");
            }
        } catch (Exception e) {
            log.error("生成支付参数异常", e);
            result.put("success", false);
            result.put("message", "生成支付参数异常: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 查询订单状态
     */
    @GetMapping("/query/{outTradeNo}")
    public ResponseEntity<Map<String, Object>> queryOrder(@PathVariable String outTradeNo) {
        Map<String, Object> result = new HashMap<>();

        try {
            WechatPayOrderResponse response = wechatPayService.queryOrder(outTradeNo);
            if (response != null && "SUCCESS".equals(response.getReturnCode())) {
                result.put("success", true);
                result.put("data", response);
                result.put("message", "查询订单成功");
            } else {
                result.put("success", false);
                result.put("data", response);
                result.put("message", response != null ? response.getReturnMsg() : "查询订单失败");
            }
        } catch (Exception e) {
            log.error("查询订单异常", e);
            result.put("success", false);
            result.put("message", "查询订单异常: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund")
    public ResponseEntity<Map<String, Object>> refund(@Valid @RequestBody WechatRefundRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            WechatRefundResponse response = wechatPayService.refund(request);
            if (response != null && "SUCCESS".equals(response.getReturnCode()) &&
                    "SUCCESS".equals(response.getResultCode())) {
                result.put("success", true);
                result.put("data", response);
                result.put("message", "申请退款成功");
            } else {
                result.put("success", false);
                result.put("data", response);
                result.put("message", response != null ?
                        (response.getErrCodeDes() != null ? response.getErrCodeDes() : response.getReturnMsg()) :
                        "申请退款失败");
            }
        } catch (Exception e) {
            log.error("申请退款异常", e);
            result.put("success", false);
            result.put("message", "申请退款异常: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 查询退款
     */
    @GetMapping("/refund/query/{outRefundNo}")
    public ResponseEntity<Map<String, Object>> queryRefund(@PathVariable String outRefundNo) {
        Map<String, Object> result = new HashMap<>();

        try {
            WechatRefundResponse response = wechatPayService.queryRefund(outRefundNo);
            if (response != null && "SUCCESS".equals(response.getReturnCode())) {
                result.put("success", true);
                result.put("data", response);
                result.put("message", "查询退款成功");
            } else {
                result.put("success", false);
                result.put("data", response);
                result.put("message", response != null ? response.getReturnMsg() : "查询退款失败");
            }
        } catch (Exception e) {
            log.error("查询退款异常", e);
            result.put("success", false);
            result.put("message", "查询退款异常: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

}
